package categories

//该文件目前没用了 20200628
import (
	"context"
	"encoding/json"
	kithttp "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"net/http"
)

func MakeHandler(cs CategoryService) http.Handler {
	getCategoriesHandler := kithttp.NewServer(
		makeGetCategoriesEndpoint(cs),
		decodeGetCategoriesRequest,
		encodeResponse)
	createCategoryHandler := kithttp.NewServer(
		makeCreateCategoryEndpoint(cs),
		decodeCreateCategoryRequest,
		encodeResponse)

	r := mux.NewRouter()
	r.Handle("/api/v1/category", getCategoriesHandler).Methods("GET")
	r.Handle("/api/v1/category", createCategoryHandler).Methods("POST")
	return r
}

func decodeGetCategoriesRequest(_ context.Context, r *http.Request) (interface{}, error) {
	return getCategoriesRequest{}, nil
}

func decodeCreateCategoryRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var body struct {
		Id       string `json:"id"`
		Name     string `json:"name"`
		ParentId string `json:"parentId"`
		CreateAt int64  `json:"createAt"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		return nil, err
	}
	return createCategoryRequest{
		Id:              body.Id,
		Name:            body.Name,
		ParentId:        body.ParentId,
		CreateTimestamp: body.CreateAt,
	}, nil
}

func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	return json.NewEncoder(w).Encode(response)
}
